Ext.require([ 'Ext.data.*', 'Ext.grid.*' ]);

Ext.define('Param', {
	extend : 'Ext.data.Model',
	fields : [ {
		name : 'id',
		type : 'int',
		useNull : true
	}, 'value', 'name', 'paramType' ],
	validations : [ {
		type : 'length',
		field : 'email',
		min : 1
	}, {
		type : 'length',
		field : 'first',
		min : 1
	}, {
		type : 'length',
		field : 'paramType',
		min : 1
	} ]
});

Ext.example = function() {
	Ext.tip.QuickTipManager.init();
	var msgCt;

	function createBox(t, s) {
		return '<div class="msg"><h3>' + t + '</h3><p>' + s + '</p></div>';
	}
	return {
		msg : function(title, format) {
			if (!msgCt) {
				msgCt = Ext.DomHelper.insertFirst(document.body, {
					id : 'msg-div'
				}, true);
			}
			var s = Ext.String.format.apply(String, Array.prototype.slice.call(arguments, 1));
			var m = Ext.DomHelper.append(msgCt, createBox(title, s), true);
			m.hide();
			m.slideIn('t').ghost("t", {
				delay : 5000,
				remove : true
			});
		},

		init : function() {
			if (!msgCt) {
				// It's better to create the msg-div here in order to avoid re-layouts 
				// later that could interfere with the HtmlEditor and reset its iFrame.
				msgCt = Ext.DomHelper.insertFirst(document.body, {
					id : 'msg-div'
				}, true);
			}
		}
	};
}();

Ext.onReady(function() {
	Ext.example.init();
	let AppConstants = Ext.widget("AppConstants");
	var pageSizeCmb = Ext.create('Dashboard.PageSizeCmb', {
		xtype : 'PageSizeCmb',
		id : 'pageSizeCmb',
		fieldLabel : '每页行数:',
		width : 150,
		value : 100,
		labelAlign : 'right',
		listeners : {
			'change' : function(cmb, newValue, oldValue, eOpts) {
				store.setPageSize(newValue);
				store.load({
					params : {
						start : 0,
						rows : newValue
					}
				});
			},
		}
	});
	let paramTypeFilterCmb = Ext.create('Ext.form.ComboBox', {
		xtype : 'combobox',
		editable : false,
		store : Ext.create('Ext.data.Store', {
			fields : [ 'name', 'value' ],
			data : []
		}),
		value : '',
		queryMode : 'local',
		valueField : 'value',
		displayField : 'name',
		enableKeyEvents : true,
		listeners : {
			afterrender : function(p) {
				let data = AppConstants.loadParamByName('paramType');
				data.unshift({
					value : '',
					name : '全部'
				});
				p.getStore().loadData(data);
				p.setValue('');
			},
			change : function(cmb, newValue, oldValue, eOpts) {
				var store = this.up('grid').store;
				store.load();
			}
		}
	});
	var store = Ext.create('Ext.data.Store', {
		autoLoad : true,
		autoSync : true,
		model : 'Param',
		pageSize : pageSizeCmb.getValue(),
		autoLoad : {
			params : {
				start : 0,
				rows : pageSizeCmb.getValue(),
			}
		},
		proxy : {
			type : 'rest',
			url : 'param/params',
			reader : {
				type : 'json',
				rootProperty : "data.data",
				totalProperty : 'data.total',
			},
			writer : {
				type : 'json'
			},
			listeners : {
				exception : function(pr, response, operation, eOpts) {
					let repsonseObj = Ext.decode(response.responseText);
					let msg = repsonseObj.message;
					Ext.example.msg('操作失败', msg);
					store.reload();
				}
			}
		},
		listeners : {
			write : function(store, operation) {
				var record = operation.getRecords()[0],
					name = Ext.String.capitalize(operation.action),
					verb;


				if (name == 'Destroy') {
					record = operation.getRecords()[0];
					verb = 'Destroyed';
				} else {
					verb = name + 'd';
				}
				Ext.example.msg(name, Ext.String.format("{0} id: {1}", verb, record.getId()));
				store.reload();
			},
			beforeLoad : function() {
				store.getProxy().setExtraParams({
					paramType : paramTypeFilterCmb.getValue(),
				});
			},
			load : function() {
				store.getProxy().setExtraParams(
					{
						forceUpdate : false
					}
				);
			}
		}
	});

	var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
		listeners : {
			beforeedit : function(editor, context, eOpts) {
				let paramType = context.record.data.paramType;
				if (paramType == AppConstants.getParamType()) {
					Ext.example.msg('操作失败', '系统参数不允许操作');
					return false;
				}
			},
			cancelEdit : function(rowEditing, context) {
				// Canceling editing of a locally added, unsaved record: remove it
				if (context.record.phantom) {
					store.remove(context.record);
				}
			}
		}
	});
	var settingGrid = Ext.create('Ext.grid.Panel', {
		plugins : [ rowEditing ],
		region : 'center',
		title : '参数列表',
		store : store,
		// iconCls : 'icon-user',
		glyph : 'xf1c0@FontAwesome',
		columns : [ {
			text : 'id',
			width : 40,
			sortable : true,
			dataIndex : 'id'
		}, {
			text : '参数类型',
			flex : 1,
			sortable : true,
			dataIndex : 'paramType',
			field : {
				xtype : 'combobox',
				editable : false,
				store : Ext.create('Ext.data.Store', {
					fields : [ 'name', 'value' ],
					data : AppConstants.loadParamByName('paramType')
				}),
				queryMode : 'local',
				valueField : 'value',
				displayField : 'name',
			},
			editor : {
				xtype : 'combobox'
			},
			items : [ paramTypeFilterCmb ],
			renderer : function(value, metaData, record, rowIdx, colIdx, store) {
				metaData.tdStyle = "vertical-align:middle;";
				let paramTypeNameMap = AppConstants.loadParamMap('paramType');
				return paramTypeNameMap[value] || value;
			}
		}, {
			text : '参数值',
			flex : 1,
			sortable : true,
			dataIndex : 'value',
			field : {
				xtype : 'textfield'
			}
		}, {
			header : '参数名称',
			flex : 1,
			sortable : true,
			dataIndex : 'name',
			field : {
				xtype : 'textfield'
			}
		} ],
		viewConfig : {
			enableTextSelection : true,
			forceFit : false,
			stripeRows : false,
			getRowClass : function(record, rowIndex, rowParams, store) {
				let paramType = record.data && record.data.paramType;
				if (paramType == AppConstants.getParamType()) {
					return 'read-only-column';
				}
			}
		},
		dockedItems : [ {
			xtype : 'toolbar',
			items : [ {
				text : 'Add',
				glyph : 'xf067@FontAwesome',
				//iconCls : 'icon-add',
				handler : function() {
					// empty record
					let emptyRecord = new Param();
					emptyRecord.setId(null);
					store.insert(0, emptyRecord);
					rowEditing.startEdit(0, 0);
				}
			}, '-', {
				itemId : 'delete',
				text : 'Delete',
				//iconCls : 'icon-delete',
				glyph : 'xf00d@FontAwesome',
				disabled : true,
				handler : function() {
					var selection = settingGrid.getView().getSelectionModel().getSelection()[0];
					if (selection) {
						store.remove(selection);
					}
				}
			} ]
		} ],
		tools : [ {
			type : 'refresh',
			tooltip : '更新系统缓存(手动变更参数表后未重启需要点击)',
			callback : function(panel, tool, event) {
				store.getProxy().setExtraParams(
					{
						forceUpdate : true
					}
				);
				store.load();
			}
		},
			{
				glyph : 'xf08e@FontAwesome',
				tooltip : '新标签页打开',
				hidden : parent == window,
				callback : function(panel, tool, event) {
					window.open('settings.html', '_blank');
				}
			} ],
		bbar : [
			{
				xtype : 'pagingtoolbar',
				store : store,
				displayInfo : true,
				items : [
					{
						xtype : 'panel',
						bodyStyle : {
							background : '#DCE7F3',
							padding : '0 0 0 20px',
							color : '#333',
						},
						border : false,
						html : parent == window ? '参数变更后需刷新页面后生效' : '参数变更后需<a class="panel-link" href="#" onClick="parent.location.reload();">刷新</a>页面后生效'
					},
					"-",
					pageSizeCmb,
				]
			}
		]
	});
	settingGrid.getSelectionModel().on('selectionchange', function(selModel, selections) {
		settingGrid.down('#delete').setDisabled(selections.length === 0);
	});
	var panel = Ext.create('Ext.panel.Panel', {
		fullscreen : true,
		height : window.innerHeight,
		width : window.innerWidth,
		layout : 'border',
		border : 0,
		items : [
			settingGrid
		],
		renderTo : Ext.getBody()
	});

});